package storage

import (
	"context"
	"io"
	"path/filepath"
	"strings"
	"time"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

var client *minio.Client

var extMap = map[string]string{
	".zip": "application/zip",
	".mp4": "video/mp4",
	".png": "image/jpeg",
}

func NewS3Client(endpoint, accessKeyID, secretAccessKey string, useSSL bool) (err error) {
	client, err = minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	return err
}

func FputObject(ctx context.Context, bucketName, objectName, filePath string) error {
	ext := filepath.Ext(filePath)
	opt := minio.PutObjectOptions{ContentType: extMap[ext]}
	_, err := client.FPutObject(ctx, bucketName, objectName, filePath, opt)
	return err
}

func PutObject(bucketName, objectName string, size int64, object io.ReadCloser) error {
	ext := filepath.Ext(objectName)
	client.PutObject(context.Background(), bucketName, objectName, object, size, minio.PutObjectOptions{ContentType: extMap[ext]})
	return nil
}

func GetObjectUrl(bucketName, objectName string) string {
	url, err := client.PresignedGetObject(context.Background(), bucketName, objectName, time.Hour, nil)
	if err != nil {
		return ""
	}
	


	return strings.Split(url.String(), "?")[0]
}
